package cn.ecnu.search.controller;

import cn.ecnu.search.model.PaperModel;
import cn.ecnu.search.parameter.SearchParameter;
import cn.ecnu.search.parameter.SearchResult;
import cn.ecnu.search.service.SearchService;
import cn.ecnu.utils.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/elk")
@RestController
public class SearchController {

    @Autowired
    private SearchService searchService;

    @Autowired
    private ElasticsearchOperations operations;

    @GetMapping("/search")
    public R search(SearchParameter parameter) {
        SearchResult result = searchService.search(parameter);
        return R.ok().put("data", result);
    }

    @PostMapping("/add")
    public R add(@RequestBody PaperModel model) {
        IndexQuery q = new IndexQueryBuilder()
                .withId(model.getPaperId().toString())
                .withObject(model)
                .build();
        operations.index(q, IndexCoordinates.of("paper"));
        return R.ok();
    }

    @GetMapping("/delete/{paperId}")
    public R delete(@PathVariable("paperId") Integer paperId) {
        String id = operations.delete(paperId.toString(), IndexCoordinates.of("paper"));
        return R.ok().put("data", id);
    }

    @GetMapping("/notenum/{paperId}/{amount}")
    public R changeNoteNum(@PathVariable("paperId") Integer paperId, @PathVariable("amount") Integer amount) {
        PaperModel paperModel = operations.get(paperId.toString(), PaperModel.class);
        if (paperModel != null) {
            paperModel.setNoteNum(paperModel.getNoteNum() + amount);
            IndexQuery index = new IndexQueryBuilder()
                    .withId(paperModel.getPaperId().toString())
                    .withObject(paperModel)
                    .build();
            operations.index(index, IndexCoordinates.of("paper"));
        }
        return R.ok();
    }
}
